import router, { asyncRouter } from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

const whilte_list = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  nProgress.start()
  const token = store.getters.token
  // console.log(token)

  if (token) {
    if (to.path === '/login') {
      nProgress.done()
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfoAction')

        console.log(roles.menus)

        console.log(asyncRouter)

        const filterRoutes = asyncRouter.filter(item => roles.menus.includes(item.name))
        console.log(filterRoutes, 111)
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.puth)
      }

      next()
    }
  } else {
    if (whilte_list.includes(to.path)) {
      next()
    } else {
      nProgress.done()
      next('/login')
    }
  }
})

router.afterEach(() => {
  nProgress.done()
})
